import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app'
import store from '@/store'
let requestList = []
let clear = true
let goLogin = true //防止多次跳登录页
/**
 * 发送请求
 */
function baseRequest(url, method, data, type) {
	let Url = HTTP_REQUEST_URL,
		header = HEADER
	let access_token = store.getters.userInfo.access_token || ''
	const datas = data || {}
	if (!['/gwsj/getOpenid', '/gwsj/login'].includes(url)) {
		datas.openid = uni.getStorageSync('userInfo').openid
	}
	if (data && data.httpType == 'tenant') {
		delete data.openid
		delete data.httpType
		Url = 'https://test.jiafan-tech.cn'
		access_token =
			'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6ImVjYWZmMjllLWU4ODUtMTFlZS04NTk3LTUyNTQwMDhkNjY2ZiIsIm5hbWUiOiJcdTVmOTBcdTZkMGIiLCJ0ZWxlcGhvbmUiOiIxNTkyMzM4Mzk1MyJ9.FWz-co9tK4cECF73yNr3udHLRAgTDbGSje0EyYHQYaY'
	}
	header[TOKENNAME] = 'Bearer ' + access_token
	return new Promise((reslove, reject) => {
		if (['POST', "PUT", "DELETE"].includes(method.toUpperCase()) && requestList.includes(url)) {
			uni.showToast({
				icon: 'none',
				title: '请避免频繁操作'
			})
			reject('请避免频繁操作')
			return
		}
		if (['POST', "PUT", "DELETE"].includes(method.toUpperCase()) && !requestList.includes(url)) {
			requestList.push(url)
		}
		if (clear && requestList.length) {
			clear = false
			setTimeout(() => {
				requestList = []
				clear = true
			}, 2000)
		}
		uni.request({
			url: url.includes('http') ? url : Url + url,
			method: method || 'GET',
			header: header,
			data: datas,
			success: (res) => {
				if (res.statusCode == 200) {
					reslove(res.data.data || res.data)
				} else if ([422, 400, 500].indexOf(res.statusCode) !== -1) {
					let message = res.data.error.message || '请求出错了'
					if (res.data.detail instanceof Array) {
						message = res.data.detail[0].msg
					}
					uni.showToast({
						title: message,
						icon: 'none',
						duration: 2000,
					})
					reject(res.data || res)
				} else if ([401].indexOf(res.statusCode) !== -1) {
					//登录过期自动登录
					reject(res.data, res)
					if (goLogin) {
						goLogin = false
						uni.showToast({
							title: "登录过期，请重新登录",
							icon: 'none',
							duration: 1000
						})
						setTimeout(function() {
							goLogin = true
							uni.navigateTo({
								url: "/pages/login",
							});
						}, 1500);
					}
				} else {
					uni.showToast({
						title: res.data.error.message,
						icon: 'none',
						duration: 1000,
					})
				}
			},
			fail: (msg) => {
				uni.showToast({
					title: res.statusCode + '请求失败,请检查网络状态',
					icon: 'none',
					duration: 1000,
				})
			},
		})
	})
}
const request = {}

;
['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (api, data, opt) => baseRequest(api, method, data, opt || {})
})

export default request